package com.springbootdf.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springbootdf.Dto.GameDto;
import com.springbootdf.common.Result;
import com.springbootdf.entity.Game;
import com.springbootdf.entity.RuleGame;
import com.springbootdf.entity.Rules;
import com.springbootdf.entity.User;
import com.springbootdf.mapper.GameMapper;
import com.springbootdf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wy
 * @since 2022-08-18
 */
@RestController
@RequestMapping("/game")
public class GameController {

    @Autowired
    private GameService gameService;

    @Autowired
    private IRulesService rulesService;
    @Autowired
    private UserService   userService;

    @Autowired
    private GameMapper gameMapper;
    @Autowired
    private IRuleGameService ruleGameService;


    public List<GameDto> items ;


    @Autowired
    private JudgeGameService JudgeGameService;

    @GetMapping("/judge")
    public Result selectJudges(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("role","裁判员");
        List<User> list = userService.list(wrapper);
        return Result.success(list);
    }
    @GetMapping("/rules")
    public Result selectRules(){

        List<Rules> list = rulesService.list();
        return Result.success(list);
    }
    @PostMapping("/add")
    public Result add(@RequestBody Game game){

        return Result.success(gameService.saveOrUpdate(game));
    }

//    @PostMapping("/addRule")
//    public Result addRule(@RequestBody RuleGame ruleGame){
//
//        return Result.success(ruleGameService.saveOrUpdate(ruleGame));
//    }
    @PostMapping("/addJudge/{gameId}")
    public Result addJudge(@PathVariable Integer gameId, @RequestBody Integer judge){
        System.out.println("==========addjudgeid======="+ judge);
        gameService.setRoleMenu(gameId, judge);
        return Result.success();
    }

    @GetMapping("/rules/{gameId}")
    public Result getRules(@PathVariable Integer gameId){
        List<Rules> rules=gameMapper.selectRulesByGameId(gameId);
        return Result.success(rules);
    }
    @GetMapping
    public IPage<Game> findPages(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "5") Integer pageSize,
                                 @RequestParam(defaultValue = "") String gamename){
        IPage<Game> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Game> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotEmpty(gamename)){
            queryWrapper.like(Game::getGameName,gamename);
        }
        return gameService.page(page,queryWrapper);
    }
    public void setItems(List<GameDto> items) {
        this.items = items;
    }

    public String ItemtoString() {
        return "GameController{" +
                "items=[" + items.get(0).toString() + items.get(1).toString() +
                "]}";
    }


    @GetMapping("/page")
    public Result findGame(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "5") Integer pageSize,
                           @RequestParam(defaultValue = "") String gamename){

        Page<GameDto> page = gameService.findPage(new Page<>(pageNum, pageSize), gamename);
        items = page.getRecords();
        int index = 0;
        for (GameDto item : items) {
            Integer id = item.getId();
            System.out.println("=========id========"+id);
            List<String> judges = JudgeGameService.findjudge(id);
            System.out.println("=======judges============"+judges.toString());
            item.setJudges(judges);
            System.out.println("item = " + item.toString());
            items.set(index++,item);
        }
        page.setRecords(items);
//        System.out.println("==============items===============");
//        System.out.println(ItemtoString());
//        System.out.println("==============items===============");
        return Result.success(page);
    }
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        return Result.success(gameService.removeById(id));
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        return Result.success(gameService.getById(id));
    }
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Game> list = gameService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("gameName", "比赛名");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("endTime", "创建时间");
        writer.addHeaderAlias("cover", "封面");
        writer.addHeaderAlias("master", "主持人");
        writer.addHeaderAlias("description", "简介");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("比赛信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Game> games = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Game game = new Game();
            game.setGameName(row.get(0).toString());
            game.setCover(row.get(1).toString());
            game.setCreateTime(row.get(2).toString());
            game.setEndTime(row.get(3).toString());
            game.setMaster(row.get(4).toString());
            game.setDescription(row.get(5).toString());
            games.add(game);
        }

        gameService.saveBatch(games);
        return Result.success(true);
    }
}

